import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

/// 裁剪工具类
class ImageClipUtil {
  static Future<Uint8List> cropImage(
      {required Uint8List imageData, required double top}) async {
    ui.Image originalImage = await decodeImageFromList(imageData);
    top = top * originalImage.height / ScreenUtil().screenHeight;
    // 创建一个新的画布
    ui.PictureRecorder recorder = ui.PictureRecorder();
    Canvas canvas = Canvas(recorder);
    // 在画布上绘制裁剪后的图像
    canvas.drawImageRect(
      originalImage,
      Rect.fromLTWH(0, top, originalImage.width.toDouble(),
          originalImage.height.toDouble()),
      Rect.fromLTWH(0, 0, originalImage.width.toDouble(),
          originalImage.height.toDouble()),
      Paint(),
    );
    // 完成并获取最终图像
    ui.Image croppedImage = await recorder
        .endRecording()
        .toImage(originalImage.width, (originalImage.height - top).toInt());
    // 将图像编码为字节列表
    ByteData? byteData =
        await croppedImage.toByteData(format: ui.ImageByteFormat.png);
    return byteData!.buffer.asUint8List();
  }
}
